#!/usr/bin/env bash

set -eu
set -o pipefail

get_prs() {
    curl -H "Authorization: token $GITHUB_API_TOKEN" \
        "https://api.github.com/repos/$PROJECT_SLUG/pulls?state=closed"
}

get_pr_meta() {
    local author_name="$1" ref="$2"
    cat - | jq -r --arg author_name "$author_name" --arg ref "$ref" '.[] | select(.head.ref == $ref and .head.user.login == $author_name and .head.repo.fork == true) | .number'
}

main() {
    local -r branch_base=$(git log --oneline -1 --format="%s" | grep "Merge pull request" | awk '$0=$NF')

    if [[ -z "$branch_base" ]]; then
        echo "It may not be a pull request. exit with zero." >&2
        exit 0
    fi

    local -r username=$(echo $branch_base | tr '/' ' ' | awk '$0=$1');
    local branch_name=$(echo $branch_base | sed "s/$username\///")

    if [[ "$username" == "$PROJECT_USERNAME" ]] && [[ "$branch_name" == "master" || "$branch_name" == "release" ]]; then
        echo "Never destroy these distributions"
        exit 0
    fi

    local -r pr_num=$(get_prs | get_pr_meta "$username" "$branch_name")

    if [[ -n "$pr_num" ]]; then
        branch_name="pull/$pr_num"
    fi

    source <(dpg procedure app-manage expose)
    export DPG_DISTRIBUTION_NAME="$branch_name"

    dpg procedure app-manage on-deploy-branch --android --app-id io.github.droidkaigi.confsched2019.debug
}

main || : # suppress an error

echo "Tried to delete ${DPG_DISTRIBUTION_NAME:-could not retrieve}" >&2
